package com.lang.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件大小
 */
public class FileSize {

    public final static DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.##");

    public static Long B(Long B) {
        return B;
    }

    public static Long KB(Long KB) {
        return B(KB) * 1024;
    }

    public static Long MB(Long MB) {
        return KB(MB) * 1024;
    }

    public static Long GB(Long GB) {
        return MB(GB) * 1024;
    }

    public static Long TB(Long TB) {
        return GB(TB) * 1024;
    }

    /**
     * @param fileSize 文件大小
     * @return 返回带单位 保留两位小数的 大小信息
     */
    public static String prettySizeRound(Long fileSize) {
        String unit;
        BigDecimal divide;
        if (fileSize > TB(1L)) {
            unit = "TB";
            divide = BigDecimal.valueOf(TB(1L));
        } else if (fileSize > GB(1L)) {
            unit = "GB";
            divide = BigDecimal.valueOf(GB(1L));
        } else if (fileSize > MB(1L)) {
            unit = "MB";
            divide = BigDecimal.valueOf(MB(1L));
        } else if (fileSize > KB(1L)) {
            unit = "KB";
            divide = BigDecimal.valueOf(KB(1L));
        } else {
            unit = "B";
            divide = BigDecimal.valueOf(B(1L));
        }
        return DECIMAL_FORMAT.format(BigDecimal.valueOf(fileSize).divide(divide, 3, RoundingMode.HALF_UP)) + unit;
    }

    /**
     * @param fileSize 文件大小
     * @return 返回带单位 精确的 大小信息
     */
    public static String prettySizeExact(Long fileSize) {
        long tb = fileSize / TB(1L);
        fileSize = fileSize - TB(tb);
        long gb = fileSize / GB(1L);
        fileSize = fileSize - GB(gb);
        long mb = fileSize / MB(1L);
        fileSize = fileSize - MB(mb);
        long kb = fileSize / KB(1L);
        fileSize = fileSize - KB(kb);
        long b = fileSize;
        List<String> builder = new ArrayList<>();
        if (tb > 0)
            builder.add(tb + "TB");
        if (gb > 0)
            builder.add(gb + "GB");
        if (mb > 0)
            builder.add(mb + "MB");
        if (kb > 0)
            builder.add(kb + "KB");
        if (b > 0)
            builder.add(b + "B");
        return String.join(".", builder);
    }
}
